﻿using System;
using StackExchange.Redis;

namespace Flagwind.Externals.Redis
{
	internal static class Utility
	{
		public static T ConvertValue<T>(object value)
		{
			if(value == null)
				return default(T);

			if(typeof(T) == typeof(string) || Flagwind.Common.TypeExtension.IsScalarType(typeof(T)))
				return Flagwind.Common.Convert.ConvertValue<T>(value);

			if(value is string)
				return Flagwind.Runtime.Serialization.Serializer.Json.Deserialize<T>((string)value);

			//强制转换，可能会导致无效转换异常
			return (T)value;
		}

		public static StackExchange.Redis.RedisValue GetStoredValue(object value)
		{
			if(value == null)
				return RedisValue.Null;

			var type = value.GetType();

			if(type == typeof(string))
				return (string)value;

			if(type.IsPrimitive || type.IsEnum || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(DateTimeOffset) || type == typeof(TimeSpan) || type == typeof(Guid) || value is System.Text.StringBuilder)
				return value.ToString();

			var serializable = value as Flagwind.Runtime.Serialization.ISerializable;

			if(serializable != null)
			{
				using(var stream = new System.IO.MemoryStream())
				{
					serializable.Serialize(stream);
					return stream.ToArray();
				}
			}

			return Flagwind.Common.Convert.ConvertValue<string>(value, () =>
			{
				return Flagwind.Runtime.Serialization.Serializer.Json.Serialize(value);
			});
		}
	}
}